package com.fingard.dsp.bank.directbank.hrrz01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.hrbb01.util.Base64Util;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpReceiver;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

public class HRRZ01Base extends DirectBase implements ITcpClient {
    //protected String[] retSign = new String[]{"", ""};
    //protected String signedData = "";
    protected String[] tmpRets = new String[]{"", "", ""};
    protected String reqTime = "";

    protected static final String INSERTSEQ = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,TRANSDATE,REQSEQID,BANKREQSEQID) values (?,?,?,?,?);";
    protected static final String SELECTSEQ = "SELECT BANKREQSEQID FROM REQSEQIDMAPPING WHERE REQSEQID=? AND BANKCODE=?;";
    private static TransIDHelper idHelper = new TransIDHelper(1, 999999999);

    protected void writeCommonHeader(XmlTextWriter xmlWriter, HRRZ01Header header) throws Exception {
        if (StringHelper.isNullOrEmpty(header.bsnCode)) {
            throw new Exception("未赋值bsnCode");
        }
        String texDate = Format.Date8Format.format(new Date());
        int i = (int)(Math.random()*900000000 + 100000000);
        String reqSoId = texDate + Integer.toString(i);
        xmlWriter.writeStartDocByDeclaration(header.bsnCode + "|" + getBankConfig().getValueAsString("channel") + "|" + "1106" + "||#<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        xmlWriter.writeStartElement("reqRoot");
        xmlWriter.writeStartElement("appHdr");
        xmlWriter.writeElementString("trxNo",  "hf0" + reqSoId);
        xmlWriter.writeElementString("msgType",  header.msgType);
        if (addCstNo(header.bsnCode)) {
            xmlWriter.writeElementString("cstNo", bankFront.org);
        }
        //渠道号
        xmlWriter.writeElementString("channelNo",getBankConfig().getValueAsString("channelNo"));
        //渠道名称
        xmlWriter.writeElementString("channelName",getBankConfig().getValueAsString("channelName"));
        xmlWriter.writeElementString("trxDate", texDate);
        reqTime = Format.Time6Format.format(new Date());
        xmlWriter.writeElementString("trxTime", reqTime);
        String signFlag = "";
        if(header.msgType.equals("1002")){
            header.signature = header.bsnCode + "|" + getBankConfig().getValueAsString("channel") + "|" + texDate + "|" + reqTime +"|"+ header.signature;
            signFlag = signature(header.signature);
        }
        xmlWriter.writeElementString("signData",signFlag);
        xmlWriter.writeEndElement();
    }

    private boolean addCstNo(String bsnCode) {
        return "CBE004".equals(bsnCode) || "CBE005".equals(bsnCode) || "CBE006".equals(bsnCode) ||"CBE007".equals(bsnCode) || "CBE008".equals(bsnCode)
                || "CBE009".equals(bsnCode) || "CBE011".equals(bsnCode);
    }


    protected String[] sendToBank(String p_reqStr, String transCode,String transType, String commandCode) throws Exception {
        String[] retStr = new String[]{"", ""};
        if (StringHelper.hasAnyChar(transType) && StringHelper.hasAnyChar(commandCode)) {
            this.detailSimulateForBank(bankFront.bankCode, transType, commandCode, p_reqStr, retStr);
            if (retStr[1].length() > 0) {
                return retStr;
            }
        }
        return sendToBank(p_reqStr, transCode);
    }

    protected String[] sendToBank(String p_reqStr,String transCode) throws Exception {
        String[] retStr = new String[]{"", ""};

        WriteBankLogLn("1.提交银行的地址：" + bankFront.serverURL);
        //构造请求规范
        WriteBankLogStep2(p_reqStr);
        WebRequest tmpWebRequest = new WebRequest(bankFront.serverURL);
        tmpWebRequest.setConnectTimeout(60000);
        tmpWebRequest.setRequestProperty("Content-Type", "application/xml;charset=utf-8");
        tmpWebRequest.setRequestProperty("connection", "Close");
        String charsetName = getCharset();
        byte[] tmpToWriteBytes = p_reqStr.getBytes("UTF-8");
        retStr = tmpWebRequest.upload(tmpToWriteBytes, "UTF-8");
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }

    //进行签名
    protected String signature(String data) throws Exception {
        String signURL = bankFront.signURL;
        WriteBankLogLn("1.银行签名地址：" + signURL);
        WriteBankLogStep2(data);
        String signedData = "";
        WebRequest tmpWebRequest = new WebRequest(signURL);
        tmpWebRequest.setConnectTimeout(60000);
        tmpWebRequest.setRequestProperty("Content-Length", String.valueOf(data.length()));
        tmpWebRequest.setRequestProperty("Content-Type", "INFOSEC_SIGN/1.0");
        String charsetName = getCharset();
        byte[] tmpToWriteBytes = data.getBytes(charsetName);
        String[] retSign = tmpWebRequest.upload(tmpToWriteBytes,"UTF-8");

        if (retSign[0].length() == 0) {
            try {
                WriteBankLogLn("3.签名返回的结果：" + retSign[1]);
                XmlTextReader tmpXmlReader = new XmlTextReader(retSign[1]);
                String tmpRest = tmpXmlReader.getSimpleText("result");
                if ("0".equals(tmpRest)) {
                    WriteBankLogLn("签名成功");
                    signedData = tmpXmlReader.getSimpleText("sign");
                } else {
                    WriteBankLogLn("签名失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                WriteBankLogLn(e.getMessage());
            }

        } else {
            WriteBankLogLn("与银行签名端口通讯失败；详细信息：" + retSign[1]);
        }
        return signedData;
    }

//    protected String getDataToSign(XmlTextWriter xmlWriter) throws Exception {
//        String data = bsnCode + "|" + bankFront.org + "|" + channel + "|#" + xmlWriter.toXmlString();
//        //请求报文需要进行Base64加密
//        return Base64Util.stringToBase64(data);
//    }

    protected boolean getRet(String p_ret) {
        tmpRets = p_ret.split("\\|");
        if (tmpRets.length >= 3) {
            if ("00000000".equals(tmpRets[0])) {
                tmpRets[2] = tmpRets[2].split("#")[1];
                return true;
            }
        }
        return false;
    }

    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }
    @Override
    public void getContentLength(TcpReceiver p_receiver) throws Exception {

    }

    protected String getTrmSeqNum() {
        Date tmpDateNow = new Date();
        return Format.Date8Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

    protected  String timestampToDate(String timestamp){
        if(StringHelper.isNullOrEmpty(timestamp)){
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdf.format(new Date(Long.parseLong(timestamp))); // 时间戳转换日期
        return dateStr;
    }
    /**
     * 获取子账号序号
     * @param account
     * @return
     */
    protected  String getSonSeq(String account){
        String sonSeq = "";
        if(account == null){
            return sonSeq;
        }
        if(account.length()>3){
            sonSeq ="0" + account.substring(account.length()-3,account.length());
        }
        return sonSeq;
    }
}
